/*
 * @Description: 
 * @Author: fhw
 * @Date: 2023-03-06 14:50:18
 */
import { Injectable, UseFilters } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { isNil } from 'ramda';
import { HttpExceptionFilter } from 'src/common/http-exception.filter';
import { getPagination, throwHttp } from 'src/utlis';
import { isTrue } from 'src/utlis/tools';
import { Between, In, Repository } from 'typeorm';
import { UserService } from '../user/user.service';
import { CreateFeedbackDto, GetFeedbackPageDot } from './dto/feedback.dto';
import { FeedbackEntity } from './entities/feedback.entity';

@Injectable()
export class FeedbackService {
  constructor(
    @InjectRepository(FeedbackEntity)
    private feedbackEntityRepository: Repository<FeedbackEntity>,
    private readonly userService: UserService,
  ) { }
  @UseFilters(new HttpExceptionFilter())
  async getFeedbackPage(params: GetFeedbackPageDot) {
    try {
      const { createTimeStart, createTimeEnd, content, phone, userId } = params
      const { pageSize, pageNum } = getPagination({
        pageSize: params.pageSize,
        pageNum: params.pageNum,
      });
      const where: GetFeedbackPageDot = {
        content, phone, userId
      }
      // 创建时间筛选
      if (!isNil(createTimeStart) && !isNil(createTimeEnd)) {
        where.createDate = Between(createTimeStart, createTimeEnd);
      }
      const [data, total] = await this.feedbackEntityRepository.findAndCount({
        where: {
          ...where,
        },
        cache: true,
        skip: pageNum * pageSize,
        take: pageSize,
        order: { createDate: 'DESC' },
      });
      return {
        data,
        total,
        pageSize,
        pageNum: pageNum + 1,
      };
    } catch (error) {
      throwHttp(error.message);
    }
  }
  /** 创建问题反馈 */
  @UseFilters(new HttpExceptionFilter())
  async createFeedback(body: CreateFeedbackDto) {
    try {
      const { content, images, phone, userId } = body
      const user = await this.userService.getUserInfo(userId)
      if (!isTrue(user)) {
        throwHttp('用户不存在');
        return
      }
      const feedback = new FeedbackEntity()
      feedback.content = content
      feedback.images = images
      feedback.phone = phone
      feedback.userId = userId
      const result = await this.feedbackEntityRepository.manager.save(feedback);
      if (isTrue(result)) {
        return '问题反馈成功'
      }
      return '问题反馈失败'
    } catch (error) {
      throwHttp(error.message);
    }
  }
}
